<?php
/**
 * Created by PhpStorm.
 * User: GIGABYTE
 * Date: 2016/6/22
 * Time: 16:31
 */

namespace MMC\Statistics\BaiDu;

class ReportService extends AbstractService
{
    const METHOD_QUERY          = 'query';
    const METHOD_GET_STATUS     = 'getstatus';
    const METHOD_QUERY_TRANS    = 'query_trans';
    const STATUS_GENERATING     = 1;

    public function query($userId, $st, array $parameters = array(), $method = self::METHOD_QUERY)
    {
        $this->config->setExtra('ucid', $userId);

        $this->httpConnect->init($this->config, self::API_URL);

        $apiConnectionData = array(
            'header' => array(
                'username'      => $this->config->getUserName(),
                'password'      => $st,
                'token'         => $this->config->getToken(),
                'account_type'  => $this->config->getAccountType(),
            ),
            'body' => array(
                'serviceName'   => 'report',
                'methodName'    => $method,
                'parameterJSON' => json_encode($parameters),
            ),
        );

        return $this->httpConnect->post($apiConnectionData);
    }

    /**
     * @param array $result
     * @return bool | string
     */
    public function getReportResultId(array $result)
    {
        if (
            !isset($result['ret_head']) || !isset($result['ret_body']['responseData'])
        ) {
            return false;
        }

        $response = json_decode($result['ret_body']['responseData'], true);

        if (
            isset($result['ret_head']['status']) &&
            0 === $result['ret_head']['status'] &&
            isset($response['query']['result_id'])
        ) {
            return $response['query']['result_id'];
        }

        return false;
    }

    /**
     *
     *
     * @param array $result
     * @return bool | int | string
     */
    public function getReportData(array $result)
    {
        if (
            !isset($result['ret_head']) || !isset($result['ret_body']['responseData'])
        ) {
            return false;
        }

        $response = json_decode($result['ret_body']['responseData'], true);

        if(!isset($response['result']['status'])) {
            return false;
        }

        $status = $response['result']['status'];

        if ($status === 3 && isset($response['result']['result_url'])) {
            return file_get_contents($response['result']['result_url']);
        }

        if ($status === 1) {
            return $status;
        }

        return false;
    }

}